import os
import shutil
import LisePDF
import Translator



class PyNakes(LisePDF.LisePDF):
    """
    Main class of PyNakes as a python command line application
    Acts as a kernel, implementing the functionality apart from the GUI

    """

    def __init__(self):
        pass



    def New(self, lisePath):
        """Arguments:
        lisePath(string) -- LiSe XML file path

        """
        shutil.copyfile(os.path.join(os.path.dirname(os.path.abspath(__file__)), 
                                     'templates/new.xml'),  
                        lisePath)
        self.Open(lisePath)

    def Open(self, lisePath):
        """Arguments:
        lisePath(string) -- LiSe XML file path

        """
        LisePDF.LisePDF.__init__(self, lisePath)
        self.ReadFromXML()

    def OpenLise1(self, lisePath):
        """Arguments:
        lisePath(string) -- LiSe XML file path

        """
        LisePDF.LisePDF.__init__(self, lisePath)
        self.readFromXMLLise1()

    def Save(self, outputPath=None):
        """Arguments:
        outputPath(string) -- Optional output path for the LiSe XML. Otherwise rewrite it.

        """
        self.WriteToXML(outputPath)
        if outputPath is None:
            outputPath = self.lisePath



    def ResetWorkflow(self):
        path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'templates/new.xml')
        tmp = LisePDF.LisePDF(path)
        tmp.ReadFromXML()
        self.SetWorkflow(tmp.GetWorkflow()) 

    def CopyEsToEnMetadata(self, copyHeader=False, copyIndex=False, copyNotes=False, autotranslate=False):
        if autotranslate:
            translator = Translator.Translator()
        if copyHeader:
            self.metadata['en'].author = self.metadata['es'].author
            self.metadata['en'].title = self.metadata['es'].title
            self.metadata['en'].year = self.metadata['es'].year
            if autotranslate:
                self.metadata['en'].owner = translator.translate(self.metadata['es'].owner)
            else:
                self.metadata['en'].owner = self.metadata['es'].owner
        if copyIndex:
            if autotranslate:
                indexPlainList = self.metadata['es'].getIndexPlainList()
                for page in indexPlainList:
                    if page['type'] == 'page':
                        page['pageTitle'] = translator.translate(page['pageTitle'])
                    elif page['type'] == 'chapter':
                        page['chapterTitle'] = translator.translate(page['chapterTitle'])
                self.metadata['en'].setIndexPlainList(indexPlainList)
            else:
                self.metadata['en'].index = self.metadata['es'].index


